package handlers

import (
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"task_queue/internal/models"
	"task_queue/internal/response"
)

// MessageLogsHandler 处理消息日志相关请求
type MessageLogsHandler struct {
	db *gorm.DB
}

// NewMessageLogsHandler 创建消息日志处理器
func NewMessageLogsHandler(db *gorm.DB) *MessageLogsHandler {
	return &MessageLogsHandler{
		db: db,
	}
}

// DeleteMessageLogs 删除消息日志
// 支持多个ID参数，支持强删除和软删除
func (h *MessageLogsHandler) DeleteMessageLogs(c *gin.Context) {
	// 获取请求参数
	idsParam := c.Query("ids")
	forceDelete := c.DefaultQuery("force", "false") == "true"

	if idsParam == "" {
		response.Fail(c, http.StatusBadRequest, "缺少必要的参数：ids")
		return
	}

	// 解析ID列表
	idStrings := strings.Split(idsParam, ",")
	ids := make([]uint64, 0, len(idStrings))

	for _, idStr := range idStrings {
		id, err := strconv.ParseUint(idStr, 10, 64)
		if err != nil {
			response.Fail(c, http.StatusBadRequest, "无效的ID格式: "+idStr)
			return
		}
		ids = append(ids, id)
	}

	// 执行删除操作
	var err error
	if forceDelete {
		// 强删除 - 从数据库中永久删除记录
		err = h.db.Unscoped().Where("id IN ?", ids).Delete(&models.MessageHistory{}).Error
	} else {
		// 软删除 - 设置删除标记
		// 注意：这里假设GORM已经为MessageHistory模型配置了软删除
		// 如果没有，需要手动更新deleted_at字段
		err = h.db.Where("id IN ?", ids).Delete(&models.MessageHistory{}).Error
	}

	if err != nil {
		response.Fail(c, http.StatusInternalServerError, "删除消息日志失败: "+err.Error())
		return
	}

	response.Success(c, gin.H{
		"message":      "删除消息日志成功",
		"deleted_ids":  ids,
		"force_delete": forceDelete,
	})
}

// BatchDeleteMessageLogs 批量删除消息日志
// 支持按条件删除，如按主题、状态、时间范围等
func (h *MessageLogsHandler) BatchDeleteMessageLogs(c *gin.Context) {
	// 获取请求参数
	topic := c.Query("topic")
	mqType := c.Query("mq_type")
	status := c.Query("status")
	startTimeStr := c.Query("start_time") // 时间戳格式
	endTimeStr := c.Query("end_time")     // 时间戳格式
	forceDelete := c.DefaultQuery("force", "false") == "true"

	// 构建查询条件
	query := h.db.Model(&models.MessageHistory{})

	if topic != "" {
		query = query.Where("topic = ?", topic)
	}

	if mqType != "" {
		query = query.Where("mq_type = ?", mqType)
	}

	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 处理时间范围
	if startTimeStr != "" {
		startTime, err := strconv.ParseInt(startTimeStr, 10, 64)
		if err != nil {
			response.Fail(c, http.StatusBadRequest, "无效的开始时间格式")
			return
		}
		startDate := time.Unix(startTime, 0)
		query = query.Where("created_at >= ?", startDate)
	}

	if endTimeStr != "" {
		endTime, err := strconv.ParseInt(endTimeStr, 10, 64)
		if err != nil {
			response.Fail(c, http.StatusBadRequest, "无效的结束时间格式")
			return
		}
		endDate := time.Unix(endTime, 0)
		query = query.Where("created_at <= ?", endDate)
	}

	// 先获取符合条件的记录数
	var count int64
	if err := query.Count(&count).Error; err != nil {
		response.Fail(c, http.StatusInternalServerError, "查询记录数失败: "+err.Error())
		return
	}

	// 执行删除操作
	var err error
	if forceDelete {
		// 强删除 - 从数据库中永久删除记录
		err = query.Unscoped().Delete(&models.MessageHistory{}).Error
	} else {
		// 软删除 - 设置删除标记
		err = query.Delete(&models.MessageHistory{}).Error
	}

	if err != nil {
		response.Fail(c, http.StatusInternalServerError, "批量删除消息日志失败: "+err.Error())
		return
	}

	response.Success(c, gin.H{
		"message":       "批量删除消息日志成功",
		"deleted_count": count,
		"force_delete":  forceDelete,
		"filters": gin.H{
			"topic":      topic,
			"mq_type":    mqType,
			"status":     status,
			"start_time": startTimeStr,
			"end_time":   endTimeStr,
		},
	})
}
